package com.ljy.jymail.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Http;
import com.ljy.common.constant.AuthServerConstant;
import com.ljy.common.exception.BizCodeEnum;
import com.ljy.common.utils.R;
import com.ljy.common.vo.MemberRespVo;
import com.ljy.jymail.authserver.Feign.MemberFeignService;
import com.ljy.jymail.authserver.Feign.ThirdPartFeignService;
import com.ljy.jymail.authserver.Util.IpUtils;
import com.ljy.jymail.authserver.vo.UserLoginVo;
import com.ljy.jymail.authserver.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Controller
@Slf4j
public class LoginController {

    /*
    * 发送一个请求，直接跳转到一个页面，不做任何方法
    * springMvc的
    *   viewController：直接映射跳转方法
    *
    * */
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    MemberFeignService memberFeignService;


    /*
    * 获取图片验证码:
    * 如果是短信验证码，需要后台进行一个防刷机制
    * */
    public R sendCode(@RequestParam("phone") String phone){

        //接口防刷
        //验证码60s频率问题
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE + phone);

        if (redisCode.split("_")[1]!=null){
            long redisPhone = -1;
             redisPhone = Long.parseLong(redisCode.split("_")[1]);
            if (redisPhone!=-1){
                if(System.currentTimeMillis()-redisPhone<60000){
                    //60秒内不可以再次发送
                    return R.error(BizCodeEnum.SMS_SEND_EXCCEPTION.getCode(),BizCodeEnum.SMS_SEND_EXCCEPTION.getMsg());
                }
            }
        }

        //验证码的值
        String code = UUID.randomUUID().toString().substring(0,5)+"_"+System.currentTimeMillis();

        //将key存入redis。key=sms：code：phone，value=code
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE+phone,code,10, TimeUnit.MINUTES);
        //防止相同手机号在60秒内再次发送


        //发送短信验证码
        //
        return R.ok();
    }


    /*
    * 注册方法
    * */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes model) {
        //参数校验
        if (result.hasErrors()) {
            /*
                Map<String,String> errors = new HashMap<>();
                result.getFieldErrors().stream().map(filedError->{
                String field = filedError.getField();
                String defaultMessage = filedError.getDefaultMessage();
                errors.put(field,defaultMessage);
                return errors;
            });*/
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField
                    , fieldError -> fieldError.getDefaultMessage()));

            //flashAttribute:只需要取一次的属性
            model.addFlashAttribute("errors", collect);
            //校验出错，转发到注册页
            //转发会导致表单重复提交，此时需要使用重定向的方式
            //重定向共享数据:redirectAttributes
            //必须写域名，否则会重定向到服务器当前的端口
            return "redirect:https://48u4939222.eicp.vip/auth/register.html";
        }

        //真正的注册
        //首先校验验证码
        String code = vo.getCode();
        //真正的对比流程
//        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE + vo.getPhone());
//        if (!StringUtils.isEmpty(redisCode)){
//           if (code.equals(redisCode.split("_")[0])){
//           删除验证码
//              stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE + vo.getPhone());
//           }else {
//           验证码没有通过
//        Map<String, String> errors = new HashMap<>();
//        errors.put("code","验证码错误");
//        model.addFlashAttribute("errors",errors);
//        return "redirect:http://auth.jymail.com/register.html";
//    }

        if (!StringUtils.isEmpty(code)){
            //验证码通过
            //1-删除验证码 此处没有使用短信验证码所以不需要
            //2-调用远程服务进行注册
            R register = memberFeignService.register(vo);
            if (register.getCode()==0){
                //成功
                System.out.println("注册成功");
                return "redirect:https://48u4939222.eicp.vip/auth/login.html";
            }else {
                Map<String, String> error = new HashMap<>();
                error.put("msg",register.getData("msg",new TypeReference<String>(){}));
                model.addFlashAttribute("errors",error);
                return "redirect:https://48u4939222.eicp.vip/auth/register.html";
            }


        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            model.addFlashAttribute("errors",errors);
            return "redirect:https://48u4939222.eicp.vip/auth/register.html";
        }

    }


    @PostMapping("/login")
    public String login(@Valid UserLoginVo vo, RedirectAttributes redirectAttributes,
                        HttpSession session){

        //远程接口登录
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            //成功
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_SUCCESS_USER,data);
            return "redirect:https://48u4939222.eicp.vip";
        }else {
            //失败,重新定向到登录页,告诉其账号密码错误
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:https://48u4939222.eicp.vip/auth/login.html";
        }
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_SUCCESS_USER);
        if (attribute==null){
            return "login.html";
        }
        return "redirect:https://48u4939222.eicp.vip";
    }


    @GetMapping("/getIp")
    @ResponseBody
    public R getIp(HttpServletRequest request, Model model){
        String ipAddr = IpUtils.getIpAddr(request);
        String address = IpUtils.getAddress(ipAddr);

        System.out.println("ip地址是:"+ipAddr+"所属地是"+address);
        HashMap<String,String> ipInfo = new HashMap<>();

        return R.ok().put("ipInfo",ipInfo);
    }
}

